//
//  TFStatusPictureView.swift
//  weiboSina
//
//  Created by admin on 16/1/4.
//  Copyright © 2016年 admin. All rights reserved.
//

import UIKit
import SDWebImage
/**
 配图的最大列数
 */
let TFStatusPictureMaxCol = 3
/**
可重用ID
*/
private let TFStatusPictureCellId = "TFStatusPictureCellId"
/**
间距
*/
private let itemMargin: CGFloat = 5
/**
宽度和高度
*/
private let itemWH = (SCREEN_width - 2 * TFStatusCellMargin-2 * itemMargin) / CGFloat(TFStatusPictureMaxCol)


class TFStatusPictureView: UICollectionView,UICollectionViewDataSource {

    
    //定义属性。供外界设置数据
    var picUrls: [TFStatusPictureInfo]?{
    
        didSet{
        
            /**
            取出数量
            */
            let count = picUrls?.count ?? 0
            //显示有多少张图片
            countLabel.text = "\(count)"
            
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(calcViewSize(count))
            }
        
            /**
            刷新数据
            */
            reloadData()
            
        }
    
    }
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        
        backgroundColor = UIColor.clearColor()
        /**
        设置数据源
        */
        dataSource = self
        /**
        注册cell
        */
        registerClass(TFStatusPictureViewCell.self, forCellWithReuseIdentifier: TFStatusPictureCellId)
        
        
        //设置cell的大小
        let layOut = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        layOut.itemSize = CGSize(width: itemWH, height: itemWH)
        
        //设置间距
        layOut.minimumInteritemSpacing = itemMargin
        layOut.minimumLineSpacing = itemMargin
        
        
//     backgroundColor = RandomColor()
        
        addSubview(countLabel)
        countLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
        
    }

    
    
    //根据张数，计算配图的大小
   private func calcViewSize(count: Int)->CGSize{
    
    if count == 1 {
        // 返回那一图片的大小
        // 从缓存里面取出图片 --> key 就是图片地址
        let key = picUrls!.first!.thumbnail_pic
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        
        // 判断从缓存里面在否真的能够取出图片
        if image != nil {
            var size = image.size
            
            // 过窄的处理
            if size.width < 80 {
                
                let width: CGFloat = 80
                let height = width / size.width * size.height
                
                size.width = width
                // 约束最大的高度
                size.height = height > 150 ? 150 : height
            }else if size.width > 200 {
                // 图片过宽的处理
                let width: CGFloat = 200
                let height = width / size.width * size.height
                
                size.width = width
                size.height = height
            }
            
            // 更改 cell 的大小
            let layout = collectionViewLayout as! UICollectionViewFlowLayout
            layout.itemSize = size
            
            return size
        }else {
            // 如果没有取出来，直接返回正方形的 size
            return CGSize(width: itemWH, height: itemWH)
        }
    }else{
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
    }

    
    
    
    
    
    /**
    计算列数
    */
    var col = count > TFStatusPictureMaxCol ? TFStatusPictureMaxCol : count
    
    
    if count == 4 {
       col = 2
    }
    /**
    计算行数
    */
    let row = (count - 1)/TFStatusPictureMaxCol + 1
    
    /**
    计算宽度和高度
    */
    let width = CGFloat(col) * itemWH + CGFloat(col - 1)*itemMargin
    let height = CGFloat(row) * itemWH + CGFloat(row - 1) * itemMargin
    return CGSize(width: width, height: height)
   }
    
    // MARK: - 懒加载countLabel
    //显示当前图片的个数
    lazy var countLabel: UILabel = {
    
    let label = UILabel(textColor: UIColor.blackColor(), textSize: 35)
        return label
    }()
   
}

// MARK: - 数据源方法
extension TFStatusPictureView {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(TFStatusPictureCellId, forIndexPath: indexPath) as! TFStatusPictureViewCell
        //设置数据
        cell.picUrl = picUrls![indexPath.item]
        
        return cell
    }
    
}


//自定义cell
class TFStatusPictureViewCell: UICollectionViewCell{

//定义外界设置属性
    var picUrl: TFStatusPictureInfo?{
    
        didSet{
            
            if let urlString = picUrl?.thumbnail_pic {
            
                let url = NSURL(string: urlString)
            //显示图片
            imageView.sd_setImageWithURL(url, placeholderImage:UIImage(named: "timeline_image_placeholder"))
            }
            
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI(){
    
        
        backgroundColor = UIColor(white: 0.97, alpha: 1.0)
        //添加控件
        contentView.addSubview(imageView)
        //添加约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
    
    }
    
    // MARK: - 懒加载imageView
    private lazy var imageView: UIImageView = {
    
    let imageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        imageView.contentMode = .ScaleAspectFill
        //裁剪多余的部分
        imageView.clipsToBounds = true
    return imageView
    }()
    
}

